package com.bing.controller.LoanProducts;

import com.bing.entity.Bp.BpInfo;
import com.bing.entity.Bp.CommentsFeedbackinfo;
import com.bing.entity.LoanProducts.LoanProductinfo;
import com.bing.response.Result;
import com.bing.service.LoanProdductsinfoService;
import com.bing.service.SendMsgService;
import com.bing.service.UserService;
import com.bing.utils.utilstool.RedisUtils;
import com.bing.web.BaseController;
import com.bing.web.BaseResponse;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Mr.HRL
 * @Description: app
 * @Date: 2019-09-08 14:16
 * @Version: 1.0
 *
 * 登陆注册
 * 申请记录 意见反馈
 */
@RestController
@RequestMapping("/app")
@Component
@Aspect
@CrossOrigin
public class AppController extends BaseController {

    @Autowired
    LoanProdductsinfoService loanProdductsinfoService;
    @Autowired
    UserService userService;
    @Autowired
    SendMsgService sendMsgService;
    @Autowired
    RedisUtils redisUtils;

    public final static String SMSTIMELIMIT = "SMSLIMIT";

    @ApiOperation(value = "产品列表")
    @RequestMapping(value = "get")
    public ResponseEntity<BaseResponse> getProductList(@RequestParam(value = "productType",required=false) String productType,
                                                       @RequestParam(value = "firstPage",required=false) String firstPage,
                                                       @RequestParam(defaultValue = "1") Integer pageNum) {
        return buildSuccessResponse(loanProdductsinfoService.getProuctListBywhere(productType,firstPage,pageNum));
    }


    @ApiOperation(value = "用户登陆")
    @RequestMapping("/land")
    public Result login(String tel, HttpSession httpSession) {
        //查询是否注册过 注册过直接登陆   没有则注册
        userService.checkBp(tel);
       /* int result = userService.findUser(user);
        if (result == 0) {
            return new Result(13000, "账号不存在");
        }
        result = userService.validate(user, password);
        if (result > 0) {
            httpSession.setAttribute("login", user);
        }
        return result == 0 ? new Result(13000, "密码错误") : Result.SUCCESS;*/
       return null;
    }

    @ApiOperation(value = "意见反馈")
    @RequestMapping("/addComment")
    public ResponseEntity<BaseResponse> initCommet(@RequestBody CommentsFeedbackinfo commentsFeedbackinfo){
        userService.initCommet(commentsFeedbackinfo);
        return buildSuccessResponse();
    }

    @ApiOperation(value = "消息列表")
    @RequestMapping("/getMsg")
    public ResponseEntity<BaseResponse> getMsg(){
        return buildSuccessResponse(userService.getAppMessageInfoList());
    }

    @ApiOperation("申请注册记录")
    @RequestMapping("/getBpregList")
    public ResponseEntity<BaseResponse> getBpregList(@RequestParam String bpId){
        //获取产品预计注册数据  过滤重复产品 按客户划分
        return buildSuccessResponse(userService.getBpregList(bpId));
    }

    /**
     * 短信发送
     * @param phone
     * @return
     */
    @RequestMapping(value = "sendMsg")
    public ResponseEntity<BaseResponse> sendMsg(@RequestParam(value = "phone",required=true) String phone,
                                                @RequestParam(value = "flag",required=true) Boolean flag) throws Exception {
        Map<String, Object> stringObjectMap = new HashMap<>();
        String str = null;
        if (flag) {
            try {
                byte[] decoded = Base64.getDecoder().decode(phone);
                String decodeStr = new String(decoded);
                str = decodeStr;
                stringObjectMap = sendMsgService.sendSmsAutomatic(decodeStr);
            } catch (Exception e){
                stringObjectMap.put("state", false);
                stringObjectMap.put("message",e.getMessage());
                //String key   =  SMSTIMELIMIT+str;
               // redisUtils.delete(key);

            }
        } else {
            stringObjectMap.put("state", true);
            stringObjectMap.put("message","111");
        }
        return  buildSuccessResponse(stringObjectMap);
    }


    @ApiOperation("用户注册")
    @RequestMapping(value = "initBpinfo" )
    public ResponseEntity<BaseResponse> initBpinfo(@RequestBody BpInfo bpInfo, HttpSession httpSession){

        //校验必须要有系统内已维护的渠道id第二次登陆 打登陆标记
        if(!isMobiPhoneNum(bpInfo.getBpTel())){
            return   buildFailResponse("手机号格式不正确---"+bpInfo.getBpTel());
        }
        BpInfo num = null;
        try {
            num = userService.initBpinfo(bpInfo);
        } catch (Exception e) {
          return   buildFailResponse(e.getMessage());
        }
        num.setCompany("深圳市三巷科技有限公司");
        num.setEmail("hz_dmjk@163.com");
        httpSession.setAttribute(bpInfo.getBpTel(), bpInfo.getBpTel());
        return buildSuccessResponse(num);
    }


    public static boolean isMobiPhoneNum(String telNum){
        String regex = "^((11[0-9])|(12[0-9])|(16[0-9])|(17[0-9])|(19[0-9])|(13[0-9])|(10[0-9])|(14[0-9])|(15[0-9])|(18[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(telNum);
        return m.matches();
    }

    /**
     * @Description 退出登录
     * @Author 胡日亮
     * @Date 2017/12/21 10:18
     */
    @RequestMapping("/bpexit")
    public ResponseEntity<BaseResponse> bpexit(String tel,HttpSession httpSession) {
        httpSession.removeAttribute(tel);
        return buildSuccessResponse();
    }

}
